package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.OSSConfig;
import net.xdclass.service.FileService;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @Classname FileServiceImpl
 * @Description TODO
 * @Date 2022/4/13 14:23
 * @Created by sunhao
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

  @Autowired
  private OSSConfig ossConfig;

  @Override
  public String uploadUserHeadImg(MultipartFile file) {

    OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

    String folder = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());

    String fileName = CommonUtil.generateUUID();

    String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

    String parentFolderName = "user";

    if (!fileExit(parentFolderName)) {
      createFolder(parentFolderName);
    }

    String newFileName = parentFolderName + "/" + folder + "/" + fileName + extension;

    try {
      PutObjectResult result = ossClient.putObject(ossConfig.getBucketName(), newFileName, file.getInputStream());
      if (null != result) {
        return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + newFileName;
      }
    } catch (Exception e) {
      log.info("文件上传失败{}", e);
    } finally {
      ossClient.shutdown();
    }
    return null;
  }

  @Override
  public boolean fileExit(String objectName) {
    OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
    try {
      return ossClient.doesObjectExist(ossConfig.getBucketName(), objectName);
    } catch (Exception e) {
      log.info("判断失败{}", e);
    } finally {
      ossClient.shutdown();
    }
    return false;
  }

  @Override
  public String createFolder(String folderName) {
    OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
    try {
      PutObjectResult result = ossClient.putObject(ossConfig.getBucketName(), folderName, new ByteArrayInputStream(new byte[0]));
      log.info("返回信息{}", result.getETag());
    } catch (Exception e) {
      log.info("创建文件夹失败{}", e);
    } finally {
      ossClient.shutdown();
    }
    return "";
  }
}
